const pool = require('../config/database');

// 添加商品到购物车
const addToCart = async (userId, drugId, quantity) => {
    try {
        // 检查购物车中是否已存在该商品
        const [existing] = await pool.execute(
            'SELECT * FROM cart WHERE user_id = ? AND drug_id = ?',
            [userId, drugId]
        );

        if (existing.length > 0) {
            // 如果存在，更新数量
            const [result] = await pool.execute(
                'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND drug_id = ?',
                [quantity, userId, drugId]
            );
            return result.affectedRows;
        } else {
            // 如果不存在，添加新记录
            const [result] = await pool.execute(
                'INSERT INTO cart (user_id, drug_id, quantity) VALUES (?, ?, ?)',
                [userId, drugId, quantity]
            );
            return result.insertId;
        }
    } catch (error) {
        throw error;
    }
};

// 获取用户的购物车
const getCartByUserId = async (userId) => {
    try {
        const [rows] = await pool.execute(
            `SELECT c.*, d.name, d.price, d.image, d.stock 
             FROM cart c 
             JOIN drugs d ON c.drug_id = d.id 
             WHERE c.user_id = ?`,
            [userId]
        );
        return rows;
    } catch (error) {
        throw error;
    }
};

// 更新购物车商品数量
const updateCartItemQuantity = async (userId, drugId, quantity) => {
    try {
        const [result] = await pool.execute(
            'UPDATE cart SET quantity = ? WHERE user_id = ? AND drug_id = ?',
            [quantity, userId, drugId]
        );
        return result.affectedRows;
    } catch (error) {
        throw error;
    }
};

// 从购物车中删除商品
const removeFromCart = async (userId, drugId) => {
    try {
        const [result] = await pool.execute(
            'DELETE FROM cart WHERE user_id = ? AND drug_id = ?',
            [userId, drugId]
        );
        return result.affectedRows;
    } catch (error) {
        throw error;
    }
};

// 清空购物车
const clearCart = async (userId) => {
    try {
        const [result] = await pool.execute(
            'DELETE FROM cart WHERE user_id = ?',
            [userId]
        );
        return result.affectedRows;
    } catch (error) {
        throw error;
    }
};

module.exports = {
    addToCart,
    getCartByUserId,
    updateCartItemQuantity,
    removeFromCart,
    clearCart
}; 